package com.glwan.fixedassetapp.ui.home;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.glwan.fixedassetapp.Adapter.HomeFragmentAdapter;
import com.glwan.fixedassetapp.MainActivity;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.thread.ThreadManager;
import com.glwan.fixedassetapp.helper.RFIDDeviceInterface;
import com.glwan.fixedassetapp.model.FragmentMenuModel;
import com.glwan.fixedassetapp.ui.home.Activity.InventoryTaskActivity;
import com.glwan.fixedassetapp.ui.home.Activity.OfflineInventoryActivity;
import com.glwan.fixedassetapp.ui.home.Activity.OfflineProductActivity;
import com.glwan.fixedassetapp.ui.home.Activity.ProductActivity;
import com.glwan.fixedassetapp.ui.home.locateTag.SearchLocateTagActivity;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.POIUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {


    private Context context;

    private RFIDDeviceInterface rfidDeviceInterface;

    private POIUtil poiUtil;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        GridView gridView = root.findViewById(R.id.fragment_home_gradView);
        context = root.getContext();

        poiUtil = POIUtil.getInstance(getActivity());

        String menuType = ((MainActivity) context).getIntent().getStringExtra("menuType");

        List<FragmentMenuModel> menuList = new ArrayList<>();

        if ("1".equals(menuType)) {
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_task, R.string.inventoryTask));
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_list, R.string.product_list));
        } else {
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_list, R.string.product_list));
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_invent, R.string.inventory));
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_import, R.string.dataImport));
            menuList.add(new FragmentMenuModel(R.drawable.fragment_home_export, R.string.dataExport));
        }
        HomeFragmentAdapter homeFragmentAdapter = new HomeFragmentAdapter(this.context, menuList);
        homeFragmentAdapter.notifyDataSetChanged();
        gridView.setAdapter(homeFragmentAdapter);
        gridView.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (((HomeFragmentAdapter) adapterView.getAdapter()).menuList.get(i).getNameId()) {
                case R.string.product_list:
                    if ("1".equals(menuType)) {
                        jumpPage(ProductActivity.class, null);
                    } else {
                        jumpPage(OfflineProductActivity.class, null);
                    }
                    break;
                case R.string.inventory:
                    jumpPage(OfflineInventoryActivity.class, null);
                    break;
                case R.string.inventoryTask:
                    jumpPage(InventoryTaskActivity.class, null);
                    break;
                case R.string.tagLocate:
                    Map<String, Object> map = new HashMap<>();
                    map.put("showListView", 0);
                    jumpPage(SearchLocateTagActivity.class, map);
                    break;
                case R.string.dataImport:
                    CommonUtil.startFragmentFileManager(this);
                    break;
                case R.string.dataExport:
                    if (Build.VERSION.SDK_INT >= 24) {
                        int REQUEST_CODE_CONTACT = 101;
                        String[] permissions = {
                                Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        //验证是否许可权限
                        for (String str : permissions) {
                            if (this.context != null) {
                                if (this.context.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                                    //申请权限
                                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                                }
                            }
                        }
                    }
                    new AlertDialog.Builder(this.context).setTitle(R.string.confirmExport)
                            .setPositiveButton(R.string.exportInventoryRecord, (dialog, which) -> {
                                ThreadManager.getThreadPool().execute(() -> {
                                    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    intent.setType("application/xlsx");
                                    // 设置默认文件名
//                                    String time = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss");
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    intent.putExtra(Intent.EXTRA_TITLE, "盘点记录-" + simpleDateFormat.format(new Date()) + ".xlsx");
                                    // 用户进行文件存储位置选择
                                    startActivityForResult(intent, 5);
                                });
                            })
                            .setNegativeButton(R.string.cancel, (dialog, which) -> {
                            }).show();
                    break;
            }
        });
        return root;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == 5) {
                Uri uri = data.getData();
                // 柯基的工具类
                // 进行写文件...
                ThreadManager.getThreadPool().execute(() -> {
                    CommonUtil.openProgressDialog(getFragmentActivity(), getString(R.string.loading));
                    doDataOutput(uri);
                    CommonUtil.cancelProgressDialog(getFragmentActivity());

                });
                return;
            }
            if (Build.VERSION.SDK_INT >= 24) {
                int REQUEST_CODE_CONTACT = 101;
                String[] permissions = {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION};
                //验证是否许可权限
                for (String str : permissions) {
                    if (context != null) {
                        if (context.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        }
                    }
                }
            }
            ThreadManager.getThreadPool().execute(() -> {
                CommonUtil.openProgressDialog(getFragmentActivity(), getString(R.string.loading));
                poiUtil.readExcelFile(context,data.getData());
                CommonUtil.cancelProgressDialog(getFragmentActivity());
            });
        }

    }

    private void doDataOutput(Uri uri) {
        poiUtil.writeExcel(uri);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    private void jumpPage(Class<?> clazz, Map<String, Object> map) {

        CommonUtil.startActivity(context, clazz, map, false);

    }

    private Activity getFragmentActivity() {
        return this.getActivity();
    }
}